
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>

#include <pthread.h>

#include <sys/types.h>
#include <sys/epoll.h>

#include "linenoise.h"
#include "myqueue.h"


extern int mthrd_run( intptr_t qctx, int uiofd );



void * std_read_thread( void * parg )
{
    intptr_t qctx = (intptr_t)parg;
    char * pret;
    int tlen;

    // 
    linenoiseHistorySetMaxLen( 10 );

    //
    while ( true )  {

        pret = linenoise(">> ");
        if ( pret == NULL )  {
            break;
        }

        // post to que...
        tlen = strlen( pret );
        if ( tlen > 0 )  {
            linenoiseHistoryAdd( pret );
            msq_enqueue( qctx, tlen+1, pret );
        }
        
        free( pret );
    }

    return NULL;
}



int main( void )
{
    int iret;
    int uiofd;
    intptr_t qctx;
    pthread_t thrdid;


    uiofd = open( "/dev/uio0", (O_RDWR | O_NONBLOCK) );
    if ( uiofd < 0 )  {
        printf( "open uio0, fail, %d\r\n", uiofd );
        return 2;
    }

    //
    iret = msq_init( &qctx );
    if ( 0 != iret )  {
        printf( "msq_init fail, %d\r\n", iret );
        return 3;
    }

    iret = pthread_create( &thrdid, NULL, std_read_thread, (void *)qctx );
    if ( 0 != iret )  {
        printf( "thread create fail, %d\r\n", iret );
        return 5;
    }

    iret = mthrd_run( qctx, uiofd );
    printf("main thrd, ret = %d\n", iret );
    return 0;
}



